﻿using LJ.Abstractions.DependencyInjection;
using LJ.Abstractions.Extensions;
using LJ.Abstractions.Reflection;
using LJ.DataAccess.Abstractions;
using Microsoft.Extensions.DependencyInjection;

namespace LJ.DataAccess.EntityFrameworkCore.Internal;

public class EFDataProviderManager : IDataProviderManager
{
    private readonly IDependencyManager _dependencyManager;

    private readonly IReflectionManager _reflectionManager;
    public EFDataProviderManager(IDependencyManager dependencyManager, IReflectionManager reflectionManager)
    {
        _dependencyManager = dependencyManager;
        _reflectionManager = reflectionManager;


        //查找所有自动注册的服务实现类型进行注册
        var types = FindTypes();
        foreach (Type type in types)
        {
            var implementedInterfaces = _dependencyManager.GetImplementedInterfaces(type);

            foreach (var implementedInterface in implementedInterfaces)
            {
                _dependencyManager.ServiceCollection.AddScoped(implementedInterface, type);
            }

        }
    }

    private List<Type> FindTypes()
    {
        Type[] baseTypes = [typeof(IDataProvider)];
        return _reflectionManager.GetTypes(type => baseTypes.Any(b => type.IsDeriveClassFrom(b)));
    }
}
